import axios from "axios";

export default {
  namespaced: true,

  state: () => ({
    curPy: "",
    cities: [],
  }),

  getters: {
    group(state) {
      const result = [];

      state.cities.forEach((city) => {
        // 1. 获取当前 city 的拼音首字母
        const py = city.pinyin[0].toUpperCase();

        // 2. 获取 py 在 result 中对应 groupName 的下标
        const index = result.findIndex((item) => item.groupName === py);

        // 3. 判断 index 是否 > -1
        if (index > -1) {
          result[index].groupList.push(city);
        } else {
          result.push({
            groupName: py,
            groupList: [city],
          });
        }
      });

      return result.sort((a, b) => (a.groupName > b.groupName ? 1 : -1));
    },

    pys(state, getters) {
      return getters.group.map((item) => item.groupName);
    },

    hotCitys(state) {
      return state.cities.filter((item) => item.isHot === 1);
    },
  },

  mutations: {
    setCurPy(state, payload) {
      state.curPy = payload;
    },

    setCities(state, payload) {
      state.cities = payload;
    },
  },

  actions: {
    async refresh({ commit }) {
      try {
        const { data: result } = await axios.get(
          "https://m.maizuo.com/gateway?k=3418365",
          {
            headers: {
              "X-Host": "mall.film-ticket.city.list",
            },
          }
        );
        if (result.status !== 0) {
          return alert(result.msg);
        }

        // this.cities = result.data.cities;
        commit("setCities", result.data.cities);
      } catch (error) {
        console.error("error", error);
      }
    },
  },
};
